package com.zkt.oss.config;

import com.zkt.oss.adapter.StorageAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ClassUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 赵开泰
 * @program jc-club
 * @date 2025/3/17 22:24
 * @description 存储服务配置类
 **/

@Configuration
@RefreshScope
public class StorageConfig {
	
	@Value("${storage.service.type}")
	private String storageType;
	
	private final Map<String, StorageAdapter> storageAdapters = new HashMap<>();
	
	public StorageConfig() throws Exception {
		// 创建类路径扫描器
		ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
		
		// 添加过滤器：只扫描实现了 StorageService 接口的类
		TypeFilter filter = new AssignableTypeFilter(StorageAdapter.class);
		scanner.addIncludeFilter(filter);
		
		// 扫描类路径
		String basePackage = "com.zkt.oss.adapter.impl";
		for (BeanDefinition beanDefinition : scanner.findCandidateComponents(basePackage)) {
			// 获取类的全限定名
			String className = beanDefinition.getBeanClassName();
			Class<?> clazz;
			if (className != null) {
				clazz = ClassUtils.forName(className, null);
				
				// 创建实例
				StorageAdapter instance = (StorageAdapter) clazz.getDeclaredConstructor().newInstance();
				
				// 提取类名的第一个单词作为 key
				String simpleName = clazz.getSimpleName();
				String key = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1).split("(?=[A-Z])")[0].toLowerCase();
				
				// 将实例放入 Map
				storageAdapters.put(key, instance);
			}
		}
	}
	
	@Bean
	@RefreshScope
	public StorageAdapter storageService() {
		if (storageAdapters.containsKey(storageType)) {
			return storageAdapters.get(storageType);
		} else {
			throw new IllegalArgumentException("未找到对应的文件存储处理器");
		}
	}
	
}